package com.zongzi.stock.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class SharePreferenceUtils {

	private static final String SP_NAME = "config";
	private static SharedPreferences sp;
	private static final int MAX_CONTENT = 40;
	
	public static void PutBoolean(String key, Boolean value,Context context){
		sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); //私有数据
		Editor editor = sp.edit();//获取编辑器
		editor.putBoolean(key, value);
		editor.commit();//提交修改
	}
	
	public static Boolean getBoolean(String key, Boolean defValue,Context context){
		sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); //私有数据
		return sp.getBoolean(key, defValue);
	}
	
	public static void PutString(String key, String value,Context context){
		sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); //私有数据
		Editor editor = sp.edit();//获取编辑器
		editor.putString(key, value);
		editor.commit();//提交修改
	}
	
	public static String getString(String key, String defValue,Context context){
		sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); //私有数据
		return sp.getString(key, defValue);
	}
	
	public static void PutInt(String key, int value,Context context){
		sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); //私有数据
		Editor editor = sp.edit();//获取编辑器
		editor.putInt(key, value);
		editor.commit();//提交修改
	}
	
	public static int getInt(String key, int defValue,Context context){
		sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); //私有数据
		return sp.getInt(key, defValue);
	}

	public static void putStringList(String key, List<String> stringList, Context context) {
		JSONArray jsonArray = new JSONArray();
		for (String b : stringList) {
			jsonArray.put(b);
		}
		PutString(key, jsonArray.toString(), context);
	}

	public static List<String> getStringList(String key, Context context)
	{
		List<String> stringList = new ArrayList<>();
		try {
			JSONArray jsonArray = new JSONArray(getString(key, "[]", context));
			for (int i = 0; i < jsonArray.length(); i++) {
				stringList.add(jsonArray.getString(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stringList;
	}
}
